import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Form, Input, Button, Select, message } from 'tea-component';
import { DeployContractListResponse } from '@ide/types/ideServer';
import useAppStore from '@ide/store';
import { KeyValueItem, KeyValueList, getListInit } from '@ide/components/common/KeyValueList';
import { ExecResult } from '@ide/components/common/ExecResult';
import { VirtualMachineOptions } from '@ide/utils/enum';
import { deployContract, deployContractList, getContractFile, crossanddeploy } from '@/api';
import { setNotificationEvent } from '@ide/utils/extension';

// 日期
export function dateFormatNotification(fmt: string) {
  const date = new Date();
  const dateObj: any = {
    // "Y+": date.getFullYear(), //年份
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (const k in dateObj) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
        ? (dateObj[k])
        : (('00' + dateObj[k]).substr(('' + dateObj[k]).length)));
    }
  }
  return fmt;
};
const platformOptions = [{ value: 'linux_amd64', text: 'linux_amd64' },{ value: 'linux_arm64', text: 'linux_arm64' }];

export default function ContractDeploy({ style }: {
  style?: React.CSSProperties;
}) {
  const [virtualMachine, setVirtualMachine] = useState('DOCKER_GO');
  const [contractName, setContractName] = useState('');
  // const [projectNameOptions, setProjectNameOptions] = useState<DeployContractListResponse[]>([]);
  const [extraList, setExtraList] = useState(getListInit());
  const [submit, setSubmit] = useState(false);
  const [version, setVersion] = useState('');
  const { setEditCompileContractsVisible, isPluginReady, compileContracts, getCompileContracts } = useAppStore();
  const { server } = useAppStore();
  const [platform, setPlatform] = useState<string>('linux_amd64');
  const [chaiId, setchaiId] = useState<string>('');
  const [deploy_contract_name, setdeploy_contract_name] = useState<string>('');


  useEffect(() => {
    if (style?.display === 'block') {
      // queryDeployContractList();
      getCompileContracts();
    }
  }, [style?.display]);

  const selectContract:DeployContractListResponse|undefined = useMemo(()=>{
    return compileContracts.find((item)=>item.name === contractName);
  },[contractName])

  useEffect(()=>{
    const hasSelectContract = compileContracts.filter((contract:any) => contract.name === contractName);
    if (hasSelectContract.length === 0&&compileContracts.length) {
      setContractName(compileContracts[0].name);
    }else{
      setContractName('');
    }
  },[compileContracts])

  // const queryDeployContractList = useCallback(async () => {
  //   const data = await deployContractList({});
  //   if (data.code === 0 && data?.data) {
  //     const list = data.data.deployList;
  //     setProjectNameOptions(list);
  //     if (list.length) {
  //       const hasSelectContract = list.filter((contract:any) => contract.name === contractName);
  //       if (hasSelectContract.length === 0) {
  //         setContractName(list[0].name);
  //       }
  //     }
  //   }
  // }, [server, contractName]);

  // 获取二进制内容
  const file2BinaryString = (file: File):Promise<string> => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      const readFile = function (result: any) {
        const uint8Array = new Uint8Array(result.currentTarget.result);
        let str = '';
        for (let i = 0; i < uint8Array.length; i++) {
          str += String.fromCharCode(uint8Array[i]);
        }
        resolve(str);
      };
      reader.addEventListener('load', readFile);
      reader.readAsArrayBuffer(file);
    });
  };
  // 合约部署
  const deployContractAction = useCallback(async () => {
    if (!selectContract) {
      message.error({ content: '请选择合约名称！' });
      return;
    };
    if (!chaiId.trim()) {
      message.error({ content: '请输入发布链ID！' });
      return;
    }
    if (!deploy_contract_name.trim()) {
      message.error({ content: '请输入合约部署名！'});
      return;
    }
    if (!version.trim()) {
      message.error({ content: '请输入合约版本！' });
      return;
    }

    if (Number(version.trim()) < 1) {
      message.error({ content: '合约版本不能小于1！' });
      return;
    }

    setSubmit(true);

    // 合约部署-获取7z
    // const data = await crossanddeploy({ path: selectContract.path });
    // const file = new File([data], selectContract.path.match(/[^\\/]+$/)?.[0] ?? '-');
    // const content = await file2BinaryString(file);
    const p = extraList.filter(
      (item) => item.key.trim() !== '' && item.value.trim() !== ''
      ).reduce((val:any, item) => {
        val[item.key] = item.value;
        return val;
      }, {})
    const jsonP = JSON.stringify(p)
    const { code, msg, data } = await crossanddeploy(
      { 
            path: selectContract.path,
            platform,
            deploy_contract_name,
            chaiId,
            contract_name: contractName,
            version: version,
            contract_type: virtualMachine, // 'WASMER',
            params: jsonP === '{}' ? '' : jsonP
    },)
    setSubmit(false);
    if (code !== 0) {
      throw new Error(msg);
    } else {
      message.success({
        content: msg
      });
    }

    // const ticket = Date.now().toString();
    // (window as any).chainMaker.createUserContract({
    //   body: {
    //     deploy_contract_name,
    //     chaiId,
    //     contractName,
    //     contractVersion: version,
    //     contractFile: content,
    //     runtimeType: virtualMachine, // 'WASMER',
    //     params: extraList.filter(
    //       (item) => item.key.trim() !== '' && item.value.trim() !== ''
    //     ).reduce((val:any, item) => {
    //       val[item.key] = item.value;
    //       return val;
    //     }, {})
    //   },
    //   ticket
    // });
    // setNotificationEvent({
    //   operation: 'createUserContract',
    //   contractName: selectContract.name,
    //   contractVersion: version,
    //   eventId: ticket
    // }, ticket);

    // 请求deploy接口
    // await deployContract({ contractName: selectContract.name });
  }, [selectContract, version, virtualMachine, platform, chaiId, deploy_contract_name]);

  return (
    <div style={style} className="nav_tab">
      <Form className='side_tab_form' layout="vertical">
        <Form.Item label={
          <div className='form-label'>
            <div>选择合约(已编译)</div>
            <Button type='link' onClick={() => setEditCompileContractsVisible(true)}>管理</Button>
          </div>
        }>
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={compileContracts ? compileContracts.map((item: DeployContractListResponse) => ({ value: item.name, text: item.name })) : []}
            value={contractName}
            onChange={(value) => {
              console.log('value: ', value);
              setContractName(value);
            }}
          />
          <Form.Text className="gray-text tea-mt-1n">{selectContract?.buildTime}</Form.Text>
        </Form.Item>
        <Form.Item label="虚拟机类型">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={VirtualMachineOptions}
            value={virtualMachine}
            onChange={(value) => setVirtualMachine(value)}
          />
        </Form.Item>
        <Form.Item label="合约执行架构">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={platformOptions}
            value={platform}
            onChange={setPlatform}
          />
        </Form.Item>
        <Form.Item label="发布链ID">
          <Input
            value={chaiId}
            onChange={setchaiId}
            className="set-height"
            placeholder='请输入发布链ID'
            size="full"/>
        </Form.Item>
        
        <Form.Item label="合约部署名">
          <Input
            value={deploy_contract_name}
            onChange={setdeploy_contract_name}
            className="set-height"
            placeholder='请输入合约部署名'
            size="full"/>
        </Form.Item>
        <Form.Item label="合约版本">
          <Input
            value={version}
            onChange={setVersion}
            className="set-height"
            placeholder='请输入合约版本'
            size="full"/>
        </Form.Item>
        <Form.Item label="额外信息(选填)">
          <KeyValueList
            value={extraList}
            onChange={(item: Array<KeyValueItem>) => {
              setExtraList(item);
            }}
          />
        </Form.Item>
        <Button
          type="primary"
          className="full-btn tea-mt-4n"
          // disabled={!isPluginReady}
          onClick={deployContractAction}
          loading={submit}
        >
          合约部署
        </Button>
      </Form>
      {/* {style?.display === 'block' && <ExecResult />} */}
    </div>
  );
}
